<template>
  <el-dialog
    v-el-drag-dialog
    :title="type === 'edit' ? '编辑' : '审核'"
    :visible.sync="visible"
    width="800px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="150px">
      <el-col :span="12">
        <el-form-item label="气瓶条码:" prop="cylinderCode">
          <el-input v-model="temp.cylinderCode" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="气瓶类型:" prop="gasCylinderTypeUUId">
          <el-select
            v-model="temp.gasCylinderTypeUUId"
            filterable
            :disabled="type=='audit'"
            style="width: 100%;"
            placeholder="请选择"
            @change="handleChangeGasCylinderType"
          >
            <el-option
              v-for="(item, index) in cylinderTypeMap"
              :key="index"
              :label="item.dictShortName + '-' + item.dictName"
              :value="`${item.cylinderTypeCode}-${item.year}`"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="气瓶年份:" prop="gasCylinderYear">
          <el-date-picker
            :value="temp.gasCylinderYear"
            style="width: 100%;"
            disabled
            type="year"
            placeholder="选择年"
            value-format="yyyy"
            :picker-options="pickerOptionsYear"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="是否超检：" prop="isOverCheck">
          <el-select
            v-model="temp.isOverCheck"
            style="width: 100%;"
            :disabled="type=='audit'"
            @change="handleChangeIsOverCheck"
          >
            <el-option label="是" :value="1" />
            <el-option label="否" :value="2" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="回收单价（超检）：" prop="unitPrice">
          <el-input :value="temp.unitPrice" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="是否报废：" prop="isScrap">
          <el-select
            v-model="temp.isScrap"
            style="width: 100%;"
            :disabled="type=='audit'"
            @change="handleChangeIsScrap"
          >
            <el-option label="是" :value="1" />
            <el-option label="否" :value="2" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="回收单价（报废）：" prop="scrapUnitPrice">
          <el-input v-model="temp.scrapUnitPrice" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="回收金额：" prop="totalAmount">
          <el-input v-model="temp.totalAmount" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="回收站点：" prop="recoveryDeptOrgSNNo">
          <el-tree-select
            v-model="temp.recoveryDeptOrgSNNo"
            disabled
            clearable
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择'
            }"
            :tree-params="{
              'expand-on-click-node': false,
              'highlight-current': true,
              'filterable': true,
              props: {
                value: 'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData,
            }"
            @node-click="selectTreeChange"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="回收人：" prop="deliverymanName">
          <el-input v-model="temp.deliverymanName" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="回收时间:" prop="recoveryDate">
          <el-date-picker
            v-model="temp.recoveryDate"
            style="width: 100%;"
            disabled
            unlink-panels
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="备注:" prop="remark">
          <el-input v-model="temp.remark" type="textarea" :rows="4" show-word-limit maxlength="200" :disabled="type=='audit'" />
        </el-form-item>
      </el-col>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button v-if="type=='edit'" :loading="$loadingPlugin.edit" type="primary" @click="success">
        保存
      </el-button>
      <el-button v-if="type=='audit'" :loading="$loadingPlugin.handleNotApproved" type="danger" @click="handleAudit(2)">
        不通过
      </el-button>
      <el-button v-if="type=='audit'" :loading="$loadingPlugin.handleApproved" type="primary" @click="handleAudit(3)">
        通过
      </el-button>
    </div>
  </el-dialog>
</template>

  <script>
  import { cylinderDictSave, updateCylinderRecovery, auditCylinderRecovery } from '@/api'

  export default {
    name: 'add',
    props: {
      treeData: {
        type: Array,
        required: true
      },
      cylinderTypeMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        type: 'edit',
        preOrgId: '',
        temp: {
          cylinderCode: '',
          gasCylinderTypeId: '',
          gasCylinderTypeUUId: '',
          isOverCheck: '',
          isScrap: '',
          recoveryDeptOrgSNNo: '',
          gasCylinderYear: '',
          remark: ''
        },
        rules: {
          year: [{ required: true, message: '请选择年份', trigger: 'change' }],
          cylinderTypeCode: [{ required: true, message: '请选择气瓶类型', trigger: 'change' }],
          nonInspectionRecoveryPrice: [{ required: true, message: '请输入回收单价', trigger: 'change' }],
          exceedInspectionRecoveryPrice: [{ required: true, message: '请输入回收单价', trigger: 'change' }],
          unScrapRecoveryPrice: [{ required: true, message: '请输入未报废回收单价', trigger: 'change' }],
          scrapRecoveryPrice: [{ required: true, message: '请输入报废回收单价', trigger: 'change' }]
        },
        pickerOptionsYear: {
          disabledDate(time) {
            const currentYear = new Date().getFullYear()
            return time.getFullYear() > currentYear
          }
        }
      }
    },
    computed: {
      currentCylinderType() {
        return this.cylinderTypeMap.find(item => `${item.cylinderTypeCode}-${item.year}` === this.temp.gasCylinderTypeUUId) || {}
      }
    },
    // watch: {
    //   changeProps(newVal) {
    //     console.log('changeProps', newVal)
    //     this.temp.gasCylinderYear = String(this.currentCylinderType.year)
    //     this.temp.unitPrice = this.temp.isOverCheck === 1 ? this.currentCylinderType.exceedInspectionRecoveryPrice : this.currentCylinderType.nonInspectionRecoveryPrice
    //     this.temp.scrapUnitPrice = this.temp.isScrap === 1 ? this.currentCylinderType.scrapRecoveryPrice : this.currentCylinderType.unScrapRecoveryPrice
    //     this.temp.totalAmount = Math.min(this.unitPrice, this.scrapUnitPrice)
    //   }
    // },
    methods: {
      open(temp, type) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.type = type
          if (temp) {
            this.temp = Object.assign(this.temp, temp)
            this.temp.gasCylinderTypeUUId = `${temp.gasCylinderTypeId}-${temp.gasCylinderYear}`
          }
        })
      },
      success() {
        this.$refs.dataForm.validate(async valid => {
          if (!valid) return
          const params = {
            id: this.temp.id,
            isOverCheck: this.temp.isOverCheck,
            isScrap: this.temp.isScrap,
            unitPrice: this.temp.unitPrice,
            scrapUnitPrice: this.temp.scrapUnitPrice,
            totalAmount: this.temp.totalAmount,
            gasCylinderYear: this.temp.gasCylinderYear,
            gasCylinderTypeId: this.currentCylinderType.cylinderTypeCode,
            gasCylinderTypeName: this.currentCylinderType.dictName,
            gasCylinderTypeSpec: this.currentCylinderType.dictShortName,
            remark: this.temp.remark
          }
          console.log('params', params)
          if (this.type === 'edit') {
            this.edit(params)
          } else {
            this.edit(params)
          }
        })
      },
      async add(params) {
        await cylinderDictSave(params)
        this.resolve()
        this.visible = false
        // this.$emit('refresh')
        this.$notify({
          title: '提示',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
      },
      async edit(params) {
        await updateCylinderRecovery(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.temp = {
          cylinderCode: '',
          gasCylinderTypeId: '',
          gasCylinderTypeUUId: '',
          isOverCheck: '',
          isScrap: '',
          recoveryDeptOrgSNNo: '',
          gasCylinderYear: '',
          remark: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.temp.recoveryDeptOrgSNNo = value.orgSNNo
        this.temp.recoveryDeptId = value.orgId
      },
      handleChangeGasCylinderType() {
        this.temp.gasCylinderYear = String(this.currentCylinderType.year)
        this.handleSetPriceProps()
      },
      handleChangeIsOverCheck() {
        this.handleSetPriceProps()
      },
      handleChangeIsScrap() {
        this.handleSetPriceProps()
      },
      handleSetPriceProps() {
        this.temp.unitPrice = this.temp.isOverCheck === 1 ? this.currentCylinderType.exceedInspectionRecoveryPrice : this.currentCylinderType.nonInspectionRecoveryPrice
        this.temp.scrapUnitPrice = this.temp.isScrap === 1 ? this.currentCylinderType.scrapRecoveryPrice : this.currentCylinderType.unScrapRecoveryPrice
        this.temp.totalAmount = Math.min(this.temp.unitPrice, this.temp.scrapUnitPrice)
      },
      async handleAudit(status) {
        const params = {
          id: this.temp.id,
          cylinderStatus: status
        }
        await auditCylinderRecovery(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      }
    }
  }
  </script>

  <style lang="scss" scoped>
  .form {
    display: flex;
    flex-wrap: wrap;

    & /deep/ .el-form-item {
      width: 100%;
    }
  }
  </style>
